package com.xunshangwang.pinhaohuo.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.entity.Address;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.entity.Order;
import com.xunshangwang.pinhaohuo.entity.WechatPay;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.tools.CommonTool;
import com.xunshangwang.pinhaohuo.tools.PayHelper;
import com.xunshangwang.pinhaohuo.widgets.LoadLayout;
import com.xunshangwang.pinhaohuo.widgets.RadioFrameGroup;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.text.DecimalFormat;

import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;

/**
 * Created by xzp on 16/2/24.
 */
public class CreateOrderActivity extends BaseActivity implements View.OnClickListener{
    private int mGroupBuy;
    private String mGroupId;
    private Goods mGoods;
    private Address mAddress;
    private TextView mReceiveNameText,mPhoneText,mFullAddressText;
    private ImageView mGoodsImage;
    private TextView mGoodsNameText,mGoodsPriceText;
    private RadioFrameGroup mPayWayGroup;
    private TextView mTotalPriceText;
    private LoadLayout mLoad;
    private View mAddressContentPanel,mSelectAddressPanel;
    private PayHelper mPayHelper;
    private String mOrderId;
    private PayHelper.OnPayCallback mPayCallback=new PayHelper.OnPayCallback() {
        @Override
        public void onPayComplete(int payWay,int code,String msg) {
            mLoad.finishLoad();
            if(msg!=null)
                ToastTool.showToast(msg);
            if(mGroupBuy==0){
                Intent intent = new Intent(CreateOrderActivity.this, OrderDetailActivity.class);
                intent.putExtra("id", mOrderId);
                startActivity(intent);
                finish();
            }
            else{
                if(TextUtils.equals(mGroupId,"0")){
                    Intent intent = new Intent(CreateOrderActivity.this, OrderDetailActivity.class);
                    intent.putExtra("id", mOrderId);
                    if(code==PayHelper.PAY_SUCCESS)
                        intent.putExtra("jumpToGroup",true);
                    startActivity(intent);
                    finish();
                }
                else {
                    if(code==PayHelper.PAY_SUCCESS){
                        setResult(RESULT_OK);
                        finish();
                    }else {
                        Intent intent = new Intent(CreateOrderActivity.this, OrderDetailActivity.class);
                        intent.putExtra("id", mOrderId);
                        startActivityForResult(intent, 1);
                    }
                }
            }
            //finish();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_order);
        Bundle bundle=getIntent().getExtras();
        mGroupBuy=bundle.getInt("groupBuy",0);
        mGroupId=bundle.getString("groupId","0");
        mPayHelper=new PayHelper(this);
        mGoods= (Goods) bundle.getSerializable("goods");
        if(mGroupBuy==1)
            if(TextUtils.equals("0",mGroupId))
                getTitleText().setText("开团");
            else
                getTitleText().setText("参团");
        else
            getTitleText().setText("单独购买");
        findView();
        initView();
        requestDefaultAddress();

    }
    private void findView(){
        mReceiveNameText= (TextView) this.findViewById(R.id.receive_name_text);
        mPhoneText= (TextView) this.findViewById(R.id.mobile_phone_text);
        mFullAddressText= (TextView) this.findViewById(R.id.full_address_text);
        mGoodsImage= (ImageView) this.findViewById(R.id.goods_image);
        mGoodsNameText= (TextView) this.findViewById(R.id.goods_name_text);
        mGoodsPriceText= (TextView) this.findViewById(R.id.goods_price_text);
        mPayWayGroup= (RadioFrameGroup) this.findViewById(R.id.pay_way_group);
        mTotalPriceText= (TextView) this.findViewById(R.id.total_price_text);
        mLoad= (LoadLayout) this.findViewById(R.id.load_layout);
        mAddressContentPanel=this.findViewById(R.id.address_content_panel);
        mSelectAddressPanel=this.findViewById(R.id.select_address_panel);

    }
    private void initView(){
        this.findViewById(R.id.select_address_btn).setOnClickListener(this);
        this.findViewById(R.id.pay_btn).setOnClickListener(this);
        this.findViewById(R.id.play_introduction_btn).setOnClickListener(this);
        if(mGoods!=null) {
            Glide.with(this).load(mGoods.getImage_url()).centerCrop().into(mGoodsImage);
            mGoodsNameText.setText(mGoods.getGoods_name());
            mGoodsPriceText.setText(CommonTool.getPriceFormatString(this, mGoods, mGroupBuy));
            initTotalPrice();
        }
        mPayWayGroup.check(R.id.wechat_radio_btn);

    }
//    private void jumpToOrderDetail(boolean jumpToGroup){
//        Intent intent = new Intent(CreateOrderActivity.this, OrderDetailActivity.class);
//        intent.putExtra("id",mOrderId);
//        intent.putExtra("jumpToGroup",jumpToGroup);
//        startActivityForResult(intent,1);
//    }
//    private void initGoodsPrice(){
//        SpannableStringBuilder builder=new SpannableStringBuilder();
//        DecimalFormat format=new DecimalFormat("0.##");
//        SpannableString priceString;
//        if(mGroupBuy==0){
//            builder.append("单独购买价: ");
//            priceString=SpannableString.valueOf(format.format(mGoods.getAlone_price()));
//        }
//        else {
//            SpannableString spannableString=SpannableString.valueOf(mGoods.getGroup_number()+"人拼团价: ");
//            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this,R.color.red)),0,2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//            builder.append(spannableString);
//            priceString=SpannableString.valueOf(format.format(mGoods.getGroup_price()));
//        }
//        SpannableString unitString=SpannableString.valueOf("￥");
//        unitString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.red)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.append(unitString);
//        priceString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.red)), 0, priceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        priceString.setSpan(new AbsoluteSizeSpan(18, true), 0, priceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.append(priceString);
//        builder.append(" ");
//        SpannableString marketPriceString=SpannableString.valueOf("￥"+format.format(mGoods.getMarket_price()));
//        marketPriceString.setSpan(new StrikethroughSpan(), 0, marketPriceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        marketPriceString.setSpan(new AbsoluteSizeSpan(12, true), 0, marketPriceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.append(marketPriceString);
//        mGoodsPriceText.setText(builder);
//    }
    private void initTotalPrice(){
        DecimalFormat format=new DecimalFormat("0.00");
        SpannableString spannableString;
        if(mGroupBuy==0){
            spannableString=SpannableString.valueOf("总计: ￥"+format.format(mGoods.getAlone_price()));
        }else {
            spannableString=SpannableString.valueOf("总计: ￥"+format.format(mGoods.getGroup_price()));
        }
        spannableString.setSpan(new AbsoluteSizeSpan(12, true), 4, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.red)),4,5,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(18,true),5,spannableString.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.red)), 5,
                spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTotalPriceText.setText(spannableString);

    }
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.play_introduction_btn:
                startActivity(new Intent(this,PlayIntroductionActivity.class));
                break;
            case R.id.select_address_btn:
                Intent addressIntent=new Intent(this,ChangeAddressActivity.class);
                if(mAddress!=null)
                    addressIntent.putExtra("addressId",mAddress.getAddress_id());
                startActivityForResult(addressIntent, 0);
                break;
            case R.id.pay_btn:
                if(mGoods==null)
                    break;
                if(mAddress==null)
                {
                    ToastTool.showToast("请选择你的收货地址");
                    break;
                }
                if(mPayWayGroup.getCheckedId()==R.id.wechat_radio_btn){
                    if(!mPayHelper.isWechatSupport()){
                        ToastTool.showToast(getResources().getString(R.string.wechat_not_support_msg));
                        break;
                    }
                }else if(mPayWayGroup.getCheckedId()==R.id.alipay_radio_btn){
                    ToastTool.showToast(getResources().getString(R.string.alipay_not_support_msg));
                    break;
                }
                requestCreateOrder();
                break;
        }
    }
    private void requestCreateOrder(){
        JSONObject object=new JSONObject();
        try {
            object.put("goods_id",mGoods.getGoods_id());
            object.put("address_id",mAddress.getAddress_id());
            object.put("group_order_id",mGroupId);
            object.put("groupbuy",mGroupBuy);
        } catch (JSONException e) {
            return;
        }
        HttpTool.postJson(this, "?g=Api&m=Weuser&a=orders&token=2" + getMainApplication().getToken(), object, new JsonHttpHandler<String>() {
            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public String parseData(JSONObject object) throws Throwable {
                return object.getString("order_id");
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, String errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mLoad.finishLoad();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, String response) {
                mOrderId=response;
                requestPay();
            }
        });
    }

    private void requestPay(){
        if(mPayWayGroup.getCheckedId()==R.id.wechat_radio_btn){
            StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=appwxpay");
            builder.append("&token="+getMainApplication().getToken());
            builder.append("&order_id="+mOrderId);
            HttpTool.get(this, builder.toString(), new JsonHttpHandler<WechatPay>() {
                @Override
                public void onStart() {
                    super.onStart();
                    mLoad.startLoad();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, WechatPay errorResponse) {
                    super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                    mLoad.finishLoad();
                }

                @Override
                public WechatPay parseData(JSONObject object) throws Throwable {
                    return JSON.parseObject(object.getString("param"),WechatPay.class);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, WechatPay response) {
                    if(response==null) {
                        ToastTool.showToast("订单信息获取失败");
                        if(mGroupBuy==1 && !TextUtils.equals("0",mGroupId)){
                            Intent intent=new Intent(CreateOrderActivity.this,OrderDetailActivity.class);
                            intent.putExtra("id",mOrderId);
                            startActivityForResult(intent,1);
                        }else {
                            Intent intent=new Intent(CreateOrderActivity.this,OrderDetailActivity.class);
                            intent.putExtra("id",mOrderId);
                            startActivity(intent);
                            finish();
                        }
                        return;
                    }
                   mPayHelper.startWechatPay(response,mPayCallback);
                }
            });
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK) {
            if (requestCode == 1)
                finish();
            return;
        }
        if(requestCode==0){
            mAddress= (Address) data.getExtras().getSerializable("address");
            if(mAddress==null){
                mSelectAddressPanel.setVisibility(View.VISIBLE);
                mAddressContentPanel.setVisibility(View.GONE);
            }
            else {
                mSelectAddressPanel.setVisibility(View.GONE);
                mAddressContentPanel.setVisibility(View.VISIBLE);
                mReceiveNameText.setText(mAddress.getReceive_name());
                mPhoneText.setText(mAddress.getMobile());
                mFullAddressText.setText(mAddress.getFull_address());
            }
        }else if(requestCode==1){
            setResult(RESULT_OK);
            finish();
        }
    }

    private void requestDefaultAddress(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=address");
        builder.append("&token="+getMainApplication().getToken());
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<Address>() {

            @Override
            public Address parseData(JSONObject object) throws Throwable {
                return JSON.parseObject(object.getString("address"),Address.class);
            }

            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Address response) {
                mAddress=response;
                if(response==null){
                    mSelectAddressPanel.setVisibility(View.VISIBLE);
                    mAddressContentPanel.setVisibility(View.GONE);
                }
                else {
                    mSelectAddressPanel.setVisibility(View.GONE);
                    mAddressContentPanel.setVisibility(View.VISIBLE);
                    mReceiveNameText.setText(mAddress.getReceive_name());
                    mPhoneText.setText(mAddress.getMobile());
                    mFullAddressText.setText(mAddress.getFull_address());
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        mPayHelper.unRegisterCallback();
        super.onDestroy();

    }
}
